package com.beerandjesus.webapp.sportofkings.handicapper.struts.action;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * Date: 2/2/13
 * Time: 9:01 AM
 */
@Component
public class ZipAction extends BaseAnalyzeAction {

    private static final Logger LOG = Logger.getLogger(ZipAction.class);

    private String trackCode;
    private String raceDate;
    private InputStream zipStream;

    private String piece1 = "<!DOCTYPE html>\n" +
            "<html>\n" +
            "<head><title>";
    private String piece2 = "</title></head>\n" +
            "<body>\n" +
            "<pre>\n";

    private String piece3 = "</pre></body>\n" +
            "</html>";
    private static final String TEMP_DIR = System.getProperty("java.io.tmpdir");
    private  static final File ZIP_FILE = new File(TEMP_DIR + "/results.zip");

    public String execute() throws Exception {
        String analysisResult = readResult();
        if (analysisResult == null) {
            return ERROR;
        }
        String title = constructPageTitle(getTrackCode(), getRaceDate());
        String content = piece1 + title + piece2 + analysisResult + piece3;

        ZipOutputStream zos = null;
        LOG.info("Writing zip file to " + ZIP_FILE.getAbsolutePath());
        try {
            zos = new ZipOutputStream(new FileOutputStream(ZIP_FILE));
            ZipEntry zipEntry = new ZipEntry(title + ".html");
            zos.putNextEntry(zipEntry);
            zos.write(content.getBytes());
            zos.flush();
        } finally {
            if (zos != null) {
                zos.close();
            }
        }
        zipStream = new FileInputStream(ZIP_FILE);
        return SUCCESS;
    }


    public String getTrackCode() {
        return trackCode;
    }

    public void setTrackCode(String trackCode) {
        this.trackCode = trackCode;
    }

    public String getRaceDate() {
        return raceDate;
    }

    public void setRaceDate(String raceDate) {
        this.raceDate = raceDate;
    }

    public InputStream getZipStream() {
        return zipStream;
    }
}
